import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getToken, setToken } from '@/utils'
import { userList } from '@/constants/user'
import { getTokenFake, getToken as tokenApi, getInfo } from '@/api'
import { getQueryParams } from '@/utils/queryParams'
// import { IUserInfo } from '@/@types'

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken('token'))
  const userInfo = ref<any>({ balance: 0 })

  const login = async (): Promise<void> => {
    try {
      const url = location.href

      const obj = getQueryParams(url)

      if (obj?.token) {
        await getGameToken(obj.token)
        return
      }

      const user = obj?.user

      const params = userList[user] ?? userList.craig

      const { data } = await getTokenFake(params)

      const t = getQueryParams(data.url)?.token

      if (t) await getGameToken(t)
    } catch {
      /* empty */
    }
  }

  const getGameToken = async (templeToken: string): Promise<void> => {
    const params = { templeToken }

    const { data } = await tokenApi(params)

    setToken('token', data.token)

    void gerUserInfo()

    token.value = data.token
  }

  const gerUserInfo = async () => {
    const { data } = await getInfo()
    userInfo.value = data
  }

  const getBalance = () => {
    gerUserInfo().then()
  }

  return { token, userInfo, login, getBalance }
})
